package io.terminus.paas.profiler.service.impl

import com.alibaba.dubbo.common.Constants
import com.alibaba.dubbo.common.URL
import io.terminus.paas.profiler.AbstractProfilerService
import io.terminus.paas.profiler.model.Route
import io.terminus.paas.profiler.service.RouteService
import io.terminus.paas.profiler.utils.sync.SyncUtils
import org.springframework.stereotype.Service

/**
 * Created by gengrong on 16/3/15.
 */
@Service
class RouteServiceImpl : RouteService, AbstractProfilerService() {

    override fun findByServiceId(registryAddress: String, serviceId: String): List<Route> {
        var list: List<Route> = arrayListOf()
        return list
    }

    override fun createRoute(registryAddress: String, route: Route) {
        getRegistryService(registryAddress).register(route.toUrl())
    }

    override fun updateRoute(registryAddress: String, route: Route) {
        val id = route.id ?: throw IllegalStateException("no route id")
        val oldRoute = findRouteUrl(registryAddress, id) ?: throw IllegalStateException("Route was changed!")
        getRegistryService(registryAddress).unregister(oldRoute)
        getRegistryService(registryAddress).register(route.toUrl())
    }

    override fun deleteRoute(registryAddress: String, id: Long) {
        val oldRoute = findRouteUrl(registryAddress, id)
        oldRoute ?: throw IllegalStateException("Route was changed!")
        getRegistryService(registryAddress).unregister(oldRoute)
    }

    fun findRouteUrlPair(registryAddress: String, id: Long): Map.Entry<Long, URL>? {
        return SyncUtils.filterFromCategory(getRegistryCache(registryAddress), Constants.ROUTERS_CATEGORY, id)
    }

    fun findRoute(registryAddress: String, id: Long): Route? {
        return SyncUtils.url2Route(findRouteUrlPair(registryAddress, id))
    }

    private fun findRouteUrl(registryAddress: String, id: Long): URL? {
        return findRoute(registryAddress, id)?.toUrl()
    }

}